<template>
  <div class="app-container">
    <div>
      <avue-form
        :option="option"
        v-model="queryParams"
        ref="searchForm"
        v-show="showSearch"
        @keydown.enter="getList"
      >
        <template #menu-form>
          <el-button icon="Search" type="primary" @click="getList" class="m-l-3"
            >查询</el-button
          >
          <el-button icon="Refresh" @click="handleEmpty(searchForm)"
            >重置</el-button
          >
        </template>
      </avue-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-upload
            v-loading="uploadLoading"
            class="upload-demo pl-2"
            action="#"
            :before-upload="beforeAvatarUpload"
            :http-request="requestFile"
            accept=" .xls, .xlsx"
            :show-file-list="false"
          >
            <el-button type="primary" style="font-size: 14px"
              ><el-icon><Upload /></el-icon>导入</el-button
            >
          </el-upload>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="EditPen"
            @click="handleDel"
            :disabled="disDelete"
            >移出</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Download" @click="downUrl"
            >下载模板</el-button
          >
        </el-col>
      </el-row>

      <el-table
        v-loading="loading"
        :data="tableList"
        row-key="id"
        stripe
        row-class-name="cursor-pointer"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="supplierName" label="供应商名称" />
        <el-table-column prop="registrationNumber" label="营业执照注册号" />
        <el-table-column prop="type" label="类型" width="130">
          <template #default="scope">
            <div>
              <dict-drop
                :options="supplier_black_type"
                :value="scope.row.type"
              /></div
          ></template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>
<script setup name="SupplierManage">
import { useRouter } from 'vue-router'
import {
  listBlackList,
  delBlackList,
  importBlackList
} from '@/api/supplierManage/index'
import useCommonStore from '@/store/modules/common'
const commonStore = useCommonStore()
const router = useRouter()
const { proxy } = getCurrentInstance()

const { supplier_black_type } = proxy.useDict(
  'supplier_black_type' //黑灰名单类型
)

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    supplierName: undefined,
    supplierTaxcode: undefined,
    expireDate: undefined
  },
  ids: [],
  selectArr: [],
  total: 0,
  option: {
    labelWidth: '10',
    menuSpan: 6,
    submitBtn: false,
    menuPosition: 'left',
    // gutter: 30,
    emptyBtn: false,
    column: [
      {
        prop: 'supplierName',
        span: 3,
        placeholder: '供应商名称',
        type: 'input'
      },
      {
        prop: 'registrationNumber',
        span: 3,
        placeholder: '营业执照注册号',
        type: 'input'
      }
    ]
  },
  showSearch: true,
  disUpdate: true /* 编辑按钮是否可编辑 */,
  disDelete: true /* 关闭按钮是否可编辑 */,
  loading: false,
  tableList: [],
  followUpParam: {} // 跟进弹窗配置
})
const {
  queryParams,
  ids,
  selectArr,
  total,
  option,
  showSearch,
  disUpdate,
  disDelete,
  loading,
  tableList,
  followUpParam
} = toRefs(data)

// 初始化
async function init() {
  // 归属部门
  getList()
}
// 重置
function handleEmpty(formEl) {
  console.log('queryParams.value1==>', toRaw(queryParams.value))
  proxy.resetForm('searchForm')
  proxy.resetForm('seniorSearchForm')
  // proxy.$refs.searchForm.resetForm()
  getList()
}

// 获取数据列表
function getList() {
  loading.value = true
  console.log('queryParams.value2==>', queryParams.value)
  listBlackList(queryParams.value).then(res => {
    loading.value = false
    tableList.value = res.rows
    total.value = res.total
    console.log(' tableList.value==>', tableList.value)
  })
  console.log('获取数据')
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  selectArr.value = selection
  disUpdate.value = selection.length != 1
  disDelete.value = !selection.length
}
function goTo(url, data) {
  router.push({ path: url, query: data })
}

const uploadLoading = ref(false)
/**导入数据 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile) {
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType = ['.xls', '.xlsx'].indexOf(ext) > -1
  const isLt2M = rawFile.size / 1024 / 1024 < 200

  if (!allowType) {
    proxy.$message.error('上传文件只能是doc、docx、pdf格式!')
  } else if (!isLt2M) {
    proxy.$message.error('上传文件大小不能超过 200MB!')
  }
  return allowType && isLt2M
}
// 上传文件
async function requestFile(params) {
  uploadLoading.value = true
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  try {
    let res = await importBlackList(uploadData)
    uploadLoading.value = false
    if (res.code === 200) {
      proxy.$modal.msgSuccess('导入成功')
      getList()
    }
  } catch (error) {
    uploadLoading.value = false
  }
}

// 移出黑名单
function handleDel(row) {
  // let rowIds = row.id
  let supplierName = selectArr.value.map(item => item.supplierName)
  proxy
    .$confirm(`是否将“${supplierName.toString()}”移出黑灰名单`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      delBlackList(ids.value.toString()).then(() => {
        getList()
        proxy.$message({
          type: 'success',
          message: '移出成功!'
        })
      })
    })
    .catch(() => {})
}
// 获取培训产业模板链接/file/系统模板文件/培训产业登记表V1_20230728155654A001.xls
const downUrl = async function downUrl() {
  const url = await commonStore.getUploadTemplateDown('supplier_black_list')
  // console.info('url', url)
  window.open(url, '_blank')
}

init()
</script>
<style scoped>
.search-drawer-retract {
  color: #999999;
}
</style>
